﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tensop.Net.Tcp
{
    public class ServerReceiveEventArgs : EventArgs
    {
        private readonly int                    _Handle;
        private List<byte>                      _Data;
        private Stack<ArraySegment<byte>>       _Pool;
        readonly Client                         _Client;

        internal ServerReceiveEventArgs(Client client,byte protocol,byte version) : base()
        {
            _Client = client;
            _Handle = client.Id;
            _Pool = new Stack<ArraySegment<byte>>( 4 );
            _Data = new List<byte>( 8 );
            Protocol = protocol;
            Version = version;
        }

        internal void Put(ArraySegment<byte> data)
        {
            if (_Client.ContentLength - data.Count >= 0)
            {
                _Data.AddRange( data );
                _Client.ContentLength -= data.Count;
            }
            else
            {
                var d = new ArraySegment<byte>( data.Array, data.Offset, (_Client.ContentLength) );
                _Data.AddRange( d );
                _Client.ContentLength = 0;
            }
            _Pool.Push( data );
        }

        internal IEnumerable<ArraySegment<byte>> Get()
        {
            while (_Pool.Count > 0)
            {
                yield return _Pool.Pop();
            }
            yield break;
        }

        public int Handle { get => _Handle; }
        public byte[] Data
        {
            get {
                var data = _Data.ToArray();
                _Data.Clear();
                return data;
            }
        }
        public byte Version { get; private set; }
        public byte Protocol { get; private set; }

    }
}
